<template>
  <div class="bill-management-container">
    <div class="filter-section">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="filterForm.startDate"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="filterForm.endDate"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item label="支付方式">
          <el-select
            v-model="filterForm.paymentMethod"
            placeholder="全部"
            style="width: 150px;"
          >
            <el-option label="微信" :value="1" />
            <el-option label="支付宝" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="支出类型">
          <el-select
            v-model="filterForm.outcomeType"
            placeholder="全部"
            style="width: 150px;"
          >
            <el-option label="生活" :value="1" />
            <el-option label="住房" :value="2" />
            <el-option label="教育" :value="3" />
            <el-option label="医疗" :value="4" />
            <el-option label="娱乐" :value="5" />
            <el-option label="还款" :value="6" />
            <el-option label="其他" :value="7" />
          </el-select>
        </el-form-item>
        <el-form-item label="房屋ID">
          <el-input
            v-model="filterForm.houseId"
            placeholder="输入房屋ID"
            style="width: 150px;"
          />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input
            v-model="filterForm.email"
            placeholder="输入邮箱"
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="openAddDialog">新增账单</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-section">
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="tableLoading"
        border
      >
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="payMethod" label="支付方式" />
        <el-table-column prop="amount" label="金额">
          <template #default="{ row }">
            <span>{{ row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="houseId" label="房屋ID" />
        <el-table-column prop="outcomeWay" label="支出类型" />
        <el-table-column prop="createTime" label="创建时间">
          <template #default="{ row }">
            <span>{{ formatDate(row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <div class="dialog-section">
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="50%"
      >
        <el-form
          :model="form"
          label-width="100px"
          :rules="rules"
          ref="formRef"
        >
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" />
          </el-form-item>
          <el-form-item label="支付方式" prop="paymentMethod">
            <el-select v-model="form.paymentMethod">
              <el-option label="微信" :value="1" />
              <el-option label="支付宝" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="金额" prop="amount">
            <el-input-number v-model="form.amount" :min="0" />
          </el-form-item>
          <el-form-item label="支出类型" prop="outcomeType">
            <el-select v-model="form.outcomeType">
              <el-option label="生活" :value="1" />
              <el-option label="住房" :value="2" />
              <el-option label="教育" :value="3" />
              <el-option label="医疗" :value="4" />
              <el-option label="娱乐" :value="5" />
              <el-option label="还款" :value="6" />
              <el-option label="其他" :value="7" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确认</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { outcomebillList, outcomebillAdd, outcomeBillDel, outcomeBillUpdate } from '@/api/statement';

// 表单数据
const form = reactive({
  id: null,
  title: '',
  email: '',
  paymentMethod: null,
  amount: null,
  outcomeType: null
});

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  paymentMethod: [{ required: true, message: '请选择支付方式', trigger: 'change' }],
  amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
  outcomeType: [{ required: true, message: '请选择支出类型', trigger: 'change' }]
};

const formRef = ref(null);

// 过滤表单数据
const filterForm = reactive({
  startDate: '',
  endDate: '',
  paymentMethod: '',
  outcomeType: '',
  houseId: '',
  email: ''
});

// 表格相关
const tableData = ref([]);
const tableLoading = ref(false);
const total = ref(0);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('新增账单');

// 生命周期钩子
onMounted(() => {
  fetchBillList();
});

// 获取账单列表
const fetchBillList = async () => {
  tableLoading.value = true;
  try {
    // 处理筛选参数，确保未填写的字段传递null
    const params = {
      startTime: filterForm.startDate ? formatDate(filterForm.startDate) : null,
      endTime: filterForm.endDate ? formatDate(filterForm.endDate) : null,
      paymentMethodId: filterForm.paymentMethod || null,
      outcomeWayId: filterForm.outcomeType || null,
      houseId: filterForm.houseId || null,
      email: filterForm.email || null,
      page: currentPage.value,
      pageSize: pageSize.value
    };

    const response = await outcomebillList(params);
    tableData.value = response.data.data;
    total.value = response.data.data.length;
  } catch (error) {
    console.error('获取账单列表失败:', error);
    ElMessage.error('获取账单列表失败，请稍后重试');
  } finally {
    tableLoading.value = false;
  }
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return null;
  if (typeof date === 'number') {
    date = new Date(date);
  }
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 处理查询
const handleSearch = () => {
  currentPage.value = 1;
  fetchBillList();
};

// 重置搜索条件
const resetSearch = () => {
  Object.assign(filterForm, {
    startDate: '',
    endDate: '',
    paymentMethod: '',
    outcomeType: '',
    houseId: '',
    email: ''
  });
  handleSearch();
};

// 打开新增对话框
const openAddDialog = () => {
  Object.assign(form, {
    id: null,
    title: '',
    email: '',
    paymentMethod: null,
    amount: null,
    outcomeType: null
  });
  dialogTitle.value = '新增账单';
  dialogVisible.value = true;
};

// 打开编辑对话框
const handleEdit = (row) => {
  Object.assign(form, {
    id: row.id,
    title: row.title,
    email: row.email,
    paymentMethod: row.payMethod === '微信' ? 1 : 2,
    amount: row.amount,
    outcomeType: row.outcomeWay === '生活' ? 1 : row.outcomeWay === '住房' ? 2 : row.outcomeWay === '教育' ? 3 : row.outcomeWay === '医疗' ? 4 : row.outcomeWay === '娱乐' ? 5 : row.outcomeWay === '还款' ? 6 : 7
  });
  dialogTitle.value = '编辑账单';
  dialogVisible.value = true;
};

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该账单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await outcomeBillDel({ id: row.id });
      ElMessage.success('删除成功');
      fetchBillList();
    } catch (error) {
      console.error('删除账单失败:', error);
      ElMessage.error('删除账单失败，请稍后重试');
    }
  }).catch(() => {});
};

// 处理分页变化
const handlePageChange = (val) => {
  currentPage.value = val;
  fetchBillList();
};

// 提交表单
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const params = {
          title: form.title,
          email: form.email,
          paymentMethodId: form.paymentMethod,
          amount: form.amount,
          outcomeWayId: form.outcomeType
        };

        if (form.id) {
          // 编辑
          await outcomeBillUpdate({ id: form.id, ...params });
          ElMessage.success('编辑成功');
        } else {
          // 新增
          await outcomebillAdd(params);
          ElMessage.success('新增成功');
        }
        dialogVisible.value = false;
        fetchBillList();
      } catch (error) {
        console.error('操作失败:', error);
        ElMessage.error('操作失败，请稍后重试');
      }
    }
  });
};
</script>

<style scoped>
.bill-management-container {
  padding: 20px;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.table-section {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>